<?php

namespace app\common\model\order;

use app\common\model\redis\RedisLock;
use Exception;
use think\Db;
use think\Model;

/**
 * 售后订单模块
 * User: LK
 * Date: 2021/3/31
 */
class OrderRefundModel extends Model
{
    protected $name = 'order_refund';

    protected static $status = ['0','1','2','3','4','5'];


    /**
     * 取消售后申请
     *
     * @param int $user_id 用户ID
     * @param int $order_refund_id 售后订单ID
     */
    public function cancelApplyRefund($params)
    {
        extract($params);

        Db::startTrans();
        try {
            // 企业售后锁
            $redis_key = 'refundOrder' . $order_refund_id;
            if (!RedisLock::lock($redis_key)) {
                throw new Exception('系统繁忙,请稍后再试', 40002);
            }
            $orderRefund = $this->get($order_refund_id);

            if (!$orderRefund) {
                throw new Exception('未找到订单', 46001);
            }
            if ($orderRefund->status != 0) {
                throw new Exception('订单状态错误', 46002);
            }
            // 更改退款状态
            OrderGoodsModel::where(['id' => $orderRefund->order_goods_id])->update(['is_sales' => 0, 'refund_no' => null, 'refund_status' => null]);

            // 取消售后单
            $orderRefund->status = 5;
            $orderRefund->save();

            // 更改订单表数据
            $order_goods_sales = OrderGoodsModel::field('id,is_sales')
                ->where(['order_id' => $orderRefund->order_id, 'id' => ['<>', $orderRefund->order_goods_id]])
                ->select();
            $order_goods_sales_count = 0;
            foreach ($order_goods_sales as $row) {
                if ($row->is_sales == 0) {
                    $order_goods_sales_count += 1;
                }
            }
            if ($order_goods_sales_count == count($order_goods_sales)) {
                $update_arr['is_sales'] = 0;
                OrderModel::where(['id' => $orderRefund->order_id])->update($update_arr);
            }

            $order = OrderModel::get($orderRefund->order_id);
            $order->aftersale_status = 5;
            $oper = [
                'id' => $user_id,
            ];
            OrderAction::operAdd($order, null, $oper, 'user', '用户取消售后申请');

            RedisLock::unlock($redis_key);
            Db::commit();
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => []
            ];
        } catch (Exception $e) {
            RedisLock::unlock($redis_key);
            Db::rollback();
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }

    /**
     * 售后订单列表
     *
     * @param int $user_id 用户ID
     * @param int $status 状态:0=待审核,1=已审核(待发货),2=待收货,3=退款成功,4=拒绝,5=取消申请
     * @param int $page 页码
     * @param int $limit 每页条数
     */
    public function getRefundOrderPageList($params,$user_id)
    {
        extract($params);

        try {
            $field = [
                'id', 'refund_no', 'order_no', 'refund_price', 'cause', 'mold', 'num',
                'express_code','express_name','express_no',
                'status', 'image', 'goods_name', 'goods_spec_str', 'createtime'
            ];
            $where = [
                '$user_id' => $user_id
            ];
            if (!empty($search)){
                if(is_numeric($search)){
                    $where['refund_no'] = ['like',"%$search%"];
                }else{
                    $where['goods_name'] = ['like',"%$search%"];
                }
            }
//            if ($status && $status > 0) {
//                $where['status'] = $status;
//            }
            if(in_array($status, self::$status)){
                switch ($status){
                    case 0:
                        $where['status'] = 0;
                        break;
                    case 1:
                        $where['status'] = 1;
                        break;
                    case 2:
                        $where['status'] = 2;
                        break;
                    case 3:
                        $where['status'] = 3;
                        break;
                    case 4:
                    case 5:
                        $where['status'] = ['in',[4,5]];
                        break;
                }
            }
            $list = $this
                ->field($field)
                ->where($where)
                ->whereNull('deletetime')
                ->order('createtime', 'desc')
                ->paginate($limit, false, ['page' => $page]);
            foreach ($list as $row) {
                $row->createtime = datetime($row->createtime);
                $row->image = ImageAddDomain($row->image);
                $status_text = '';
                switch ($row->status) {
                    case 0:
                        $status_text = '待审核';
                        break;
                    case 1:
                        if ($row->mold == 1) {
                            $status_text = '待退款';
                        } else {
                            $status_text = '待寄回商品';
                        }
                        break;
                    case 2:
                        $status_text = '待收货';
                        break;
                    case 3:
                        $status_text = '退款成功';
                        break;
                    case 4:
                        $status_text = '商家拒绝';
                        break;
                    case 5:
                        $status_text = '取消申请';
                        break;

                }
                $mold_text = '';
                switch ($row->mold) {
                    case 1:
                        $mold_text = '退款';
                        break;
                    case 2:
                        $mold_text = '退货退款';
                        break;
                }
                $row->status_text = $status_text;
                $row->mold_text = $mold_text;

                // 按钮状态:0=不显示,1=显示
                $btn = [
                    'is_cancel' => 0,//取消按钮
                    'is_send' => 0,//发货按钮
                    'is_delete' => 0,//删除按钮
                ];

                switch ($row->status){
                    case 0:
                        $btn['is_cancel'] = 1;
                        break;
                    case 1:
                        if ($row->mold == 2) {
                            $btn['is_send'] = 1;
                        }
                        break;
                    case 2:
                        break;
                    case 3:
                        $btn['is_delete'] = 1;
                        break;
                    case 4:
                        $btn['is_delete'] = 1;
                        break;
                    case 5:
                        $btn['is_delete'] = 1;
                        break;
                }

                $row->btn = $btn;
            }

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        } catch (Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }

    /**
     * 售后订单详情
     *
     * @param int $order_refund_id 售后订单ID
     */
    public function refundOrderDetail($params, $user_id)
    {
        extract($params);
        try {
            $field = [
                'id', 'refund_no', 'order_no', 'refund_price', 'cause', 'mold', 'status', 'image', 'images', 'goods_name', 'goods_spec_str', 'num',
                'express_code','express_name','express_no','refuse_content',
                'createtime', 'check_time', 'refund_time'
            ];
            $data = $this->field($field)->where(['id' => $order_refund_id])->find();
            $data->sendInfo = [];
            $status = '';
            switch ($data->status) {
                case 0:
                    $status = '待审核';
                    break;
                case 1:
                    if ($data->mold == 1) {
                        $status = '待退款';
                    } else {
                        $status = '待寄回商品';
                        $data->sendInfo = [
                            'address' => config('site.refund_address'),
                            'addressee' => config('site.refund_addressee'),
                            'phone' => config('site.refund_addressee_phone'),
                        ];
                    }
                    break;
                case 2:
                    $status = '待收货';
                    $data->sendInfo = [
                        'address' => config('site.refund_address'),
                        'addressee' => config('site.refund_addressee'),
                        'phone' => config('site.refund_addressee_phone'),
                    ];
                    break;
                case 3:
                    $status = '退款成功';
                    if ($data->mold == 2) {
                        $data->sendInfo = [
                            'address' => config('site.refund_address'),
                            'addressee' => config('site.refund_addressee'),
                            'phone' => config('site.refund_addressee_phone'),
                        ];
                    }
                    break;
                case 4:
                    $status = '商家拒绝';
                    break;
                case 5:
                    $status = '取消申请';
                    break;

            }
            $mold = '';
            switch ($data->mold) {
                case 1:
                    $mold = '退款';
                    break;
                case 2:
                    $mold = '退货退款';
                    break;
            }

            // 按钮状态:0=不显示,1=显示
            $btn = [
                'is_cancel' => 0,//取消按钮
                'is_send' => 0,//发货按钮
                'is_delete' => 0,//删除按钮
            ];

            switch ($data->status){
                case 0:
                    $btn['is_cancel'] = 1;
                    break;
                case 1:
                    if ($data->mold == 2) {
                        $btn['is_send'] = 1;
                    }
                    break;
                case 2:
                    break;
                case 3:
                    $btn['is_delete'] = 1;
                    break;
                case 4:
                    $btn['is_delete'] = 1;
                    break;
                case 5:
                    $btn['is_delete'] = 1;
                    break;
            }
            $data->btn = $btn;

            if (!empty($data->images)) {
                $data->images = MoreImageDomain($data->images);
            }
            $data->image = ImageAddDomain($data->image);
            $data->createtime = datetime($data->createtime);
            $data->check_time = datetime($data->check_time);
            $data->refund_time = datetime($data->refund_time);

            $data->mold_text = $mold;
            $data->status_text = $status;

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $data
            ];
        } catch (Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }

    /**
     * 用户退货发货:填写快递单号和快递公司
     *
     * @param int $order_refund_id 售后订单ID
     * @param string $express_name 快递公司名称
     * @param string $express_no 快递单号
     */
    public function editRefundOrder($params, $user_id)
    {
        extract($params);

        try {
            $orderRefund = $this->get($order_refund_id);

            if (!$orderRefund) {
                throw new Exception('未找到订单', 46001);
            }
            if ($orderRefund->status != 1) {
                throw new Exception('订单状态错误', 46002);
            }
            $orderRefund->express_name = $express_name;
            $orderRefund->express_no = $express_no;
            $orderRefund->deliver_time = time();
            $orderRefund->status = 2;
            $orderRefund->save();

            $order = OrderModel::get($orderRefund->order_id);
            $order->aftersale_status = 2;
            $oper = [
                'id' => $user_id,
            ];
            OrderAction::operAdd($order, null, $oper, 'user', '用户退货发货');

            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => []
            ];
        } catch (Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }

    /**
     * 删除售后订单
     *
     * @param int $order_refund_id 售后订单ID
     */
    public function deleteRefund($params, $user_id)
    {
        extract($params);

        try {
            $orderRefund = $this->get($order_refund_id);
            if (!$orderRefund) {
                throw new Exception('未找到订单', 46001);
            }
            if (!in_array($orderRefund['status'], [3, 4, 5])) {
                throw new Exception('订单状态错误', 46002);
            }
            $orderRefund->deletetime = time();
            $orderRefund->save();
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => []
            ];
        } catch (Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => $e->getLine()
            ];
        }
    }
}